package com.wuhanins.insmytestdemo.base;

import android.app.Notification;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;

import androidx.multidex.MultiDexApplication;

import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.common.BaiduMapSDKException;
import com.baidu.trace.LBSTraceClient;
import com.baidu.trace.Trace;
import com.baidu.trace.api.entity.LocRequest;
import com.baidu.trace.api.entity.OnEntityListener;
import com.baidu.trace.api.track.LatestPointRequest;
import com.baidu.trace.api.track.OnTrackListener;
import com.baidu.trace.model.OnCustomAttributeListener;
import com.baidu.trace.model.ProcessOption;
import com.wuhanins.common.exception.CrashHandler;
import com.wuhanins.common.utils.ComStatic;
import com.wuhanins.insmytestdemo.BuildConfig;
import com.wuhanins.insmytestdemo.domainService.provider.utils.CommonUtil;
import com.wuhanins.insmytestdemo.domainService.provider.utils.NetUtil;
import com.wuhanins.zero2.view.InsToastUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Author  ： logan
 * Time    ： 10/12/21 2:59 PM
 * Desc    ：
 */
public class BaseApplication extends MultiDexApplication implements ComStatic.OnApplicationBuildConfig {


    private AtomicInteger mSequenceGenerator = new AtomicInteger();

    private LocRequest locRequest = null;

    private Notification notification = null;

    public Context mContext = null;

    public SharedPreferences trackConf = null;

    /**
     * 轨迹客户端
     */
    public LBSTraceClient mClient = null;

    /**
     * 轨迹服务
     */
    public Trace mTrace = null;

    /**
     * 轨迹服务ID
     */
    public long serviceId = 237831;

    /**
     * Entity标识
     */
    public String entityName = "myTrace";

    public boolean isRegisterReceiver = false;

    /**
     * 服务是否开启标识
     */
    public boolean isTraceStarted = false;

    /**
     * 采集是否开启标识
     */
    public boolean isGatherStarted = false;

    public static int screenWidth = 0;

    public static int screenHeight = 0;

    public SharedPreferences getSharedPreferences() {
        try {
            String packageName = getApplicationContext().getPackageName() + "preferences";
            Context context = this.createPackageContext(getApplicationContext().getPackageName(),
                    Context.CONTEXT_IGNORE_SECURITY);
            return context.getSharedPreferences(packageName, Context.MODE_PRIVATE);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
        startUp();
//        BitmapUtil.init();
        LBSTraceClient.setAgreePrivacy(mContext, true);
        // 若为创建独立进程，则不初始化成员变量
        if ("com.baidu.track:remote".equals(CommonUtil.getCurProcessName(mContext))) {
            return;
        }

        // 默认本地个性化地图初始化方法
        SDKInitializer.setAgreePrivacy(this, true);
        try {
            SDKInitializer.initialize(this);
        } catch (BaiduMapSDKException e) {
            e.printStackTrace();
        }
        SDKInitializer.setCoordType(CoordType.BD09LL);
        try {
            mClient = new LBSTraceClient(mContext);
        } catch (Exception e) {
            e.getMessage();
        }
        trackConf = getSharedPreferences("track_conf", MODE_PRIVATE);
        mTrace = new Trace(serviceId, entityName);
        mTrace.setNotification(notification);
        locRequest = new LocRequest(serviceId);
        if (mClient != null) {
            mClient.setOnCustomAttributeListener(new OnCustomAttributeListener() {
                @Override
                public Map<String, String> onTrackAttributeCallback() {
                    Map<String, String> map = new HashMap<>();
                    map.put("key1", "value1");
                    map.put("key2", "value2");
                    return map;
                }

                @Override
                public Map<String, String> onTrackAttributeCallback(long locTime) {
                    System.out.println("onTrackAttributeCallback, locTime : " + locTime);
                    Map<String, String> map = new HashMap<>();
                    map.put("key1", "value1");
                    map.put("key2", "value2");
                    return map;
                }
            });
        }

        clearTraceStatus();
    }

    private void startUp() {
        CrashHandler.getInstance().init(this, Static.getCrashHandlerPath());
        ComStatic.setOnApplicationBuildConfig(this);
        InsToastUtil.init(this);
        TBStartUp.newInstance().make(this);
    }

    /**
     * 清除Trace状态：初始化app时，判断上次是正常停止服务还是强制杀死进程，根据trackConf中是否有is_trace_started字段进行判断。
     * <p>
     * 停止服务成功后，会将该字段清除；若未清除，表明为非正常停止服务。
     */
    private void clearTraceStatus() {
        if (trackConf.contains("is_trace_started") || trackConf.contains("is_gather_started")) {
            SharedPreferences.Editor editor = trackConf.edit();
            editor.remove("is_trace_started");
            editor.remove("is_gather_started");
            editor.apply();
        }
    }

    /**
     * 获取当前位置
     */
    public void getCurrentLocation(OnEntityListener entityListener, OnTrackListener trackListener) {
        if (mClient == null) {
            return;
        }
        // 网络连接正常，开启服务及采集，则查询纠偏后实时位置；否则进行实时定位
        if (NetUtil.isNetworkAvailable(mContext)
                && trackConf.contains("is_trace_started")
                && trackConf.contains("is_gather_started")
                && trackConf.getBoolean("is_trace_started", false)
                && trackConf.getBoolean("is_gather_started", false)) {
            LatestPointRequest request = new LatestPointRequest(getTag(), serviceId, entityName);
            ProcessOption processOption = new ProcessOption();
            processOption.setNeedDenoise(true);
            processOption.setRadiusThreshold(100);
            request.setProcessOption(processOption);
            mClient.queryLatestPoint(request, trackListener);
        } else {
            mClient.queryRealTimeLoc(locRequest, entityListener);
        }
    }

    /**
     * 获取请求标识
     *
     * @return
     */
    public int getTag() {
        return mSequenceGenerator.incrementAndGet();
    }

    @Override
    public boolean getBuildConfig() {
        return BuildConfig.DEBUG;
    }

}